home *** CD-ROM | disk | FTP | other *** search
Text File | 1991-11-09 | 1.8 KB | 63 lines | [TEXT/KEEN] |
- #SortLibrary: a heap sort routine. PLEASE NOTE hAWK has a built-in
- #“sort” function, this file just demonstrates what a library file
- #looks like, and incidentally shows hAWK as an algorithm
- #prototyper, using a classic example. If you need to do actual
- #sorting, use the built-in “sort” function. See “$WordFrequency”
- #for an example of real sorting with hAWK.
- #
- #“hsort” stands for heap sort, a standard sorting
- #method. hsort expects to deal with numeric indexes for the
- #array A, starting with 1 rather than 0.
- #hsort compares the elements as numbers if both are numbers, otherwise
- #it compares them as strings.
- #
- #If your array is associative, use the following
- #approach to sorting it according to the order of the indexes
- #(words[] is an array indexed associatively):
- # for (w in words)
- # A[++m] = w SUBSEP words[w]
- # hsort(A, m)
- # for (j = 1; j <= m; ++j)
- # {
- # A[j] = substr(A[j], index(A[j], SUBSEP) + 1)
- # print A[j]
- # }
- #What we did there was: tack the index itself onto the beginning of
- #each array element, and load this element into a numerically–indexed
- #array; sort the new array; then loop over the new array in numeric
- #order, stripping off the index before printing.
- #To sort an associative array by the value of its elements rather than
- #its indexes, proceeed as above but don't tack the index onto the
- #front of each element of A[], ie use
- # for (w in words)
- # A[++m] = words[w]
- #as the first step.
- #
-
- function hsort(A,n, i)
- {
- for (i = int(n/2); i >= 1; i--)
- heapify(A,i,n)
- for (i = n; i> 1; i--)
- {
- swap(A,1,i)
- heapify(A,1,i-1)
- }
- }
-
- function heapify(A,left,right, p,c)
- {
- for (p = left; (c = 2*p) <= right; p = c)
- {
- if (c < right && A[c+1] > A[c])
- c++
- if (A[p] < A[c])
- swap(A,c,p)
- }
- }
-
- function swap(A,i,j, t)
- {
- t = A[i]; A[i] = A[j]; A[j] = t
- }
-